<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Console\Commands\WdtClient;
use Carbon\Carbon;


// 原始订单推送 5min
//测试执行命令  php artisan sync:TradePush
// 接口描述：①推送销售订单给ERP ；②更新已推送成功的销售订单。
// 文档地址: https://open.wangdian.cn/qyb/open/apidoc/doc?path=trade_push.php

class SyncTradePush extends Command
{
    protected $signature = 'sync:TradePush';
    protected $description = '同步创建原始订单数据到旺店api';

    //用建议：建议每间隔（5~10）分钟，将商城积累的订单集中推送，
    //每次请求包含订单条数建议不超过50条(1条订单由"trade_list+order_list"构成)，如果累积量超过了50条，分多次请求。
    //思路下单的数据写入到redis 这边定时任务区更新数据到旺店通创建订单接口

    public function handle()
    {
        Log::info('同步任务SyncTradePush', ["开始推送订单到旺店通"]);
        Log::info('同步任务SyncTradePush time', [Carbon::now()]);
        $sid = config('services.wdt.sid');
        $appKey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'trade_push.php';
        $shopNo = config('services.wdt.shopNo');
        $this->info('sid:' . $sid . " appKey:" . $appKey . " secret:" . $secret . " url:" . $url. " shopNo:" . $shopNo);
        $c = new WdtClient($sid, $appKey, $secret, $url);

        $batchSize = 50;
        $redisKey = 'order:pending:push';
        $total = Redis::llen($redisKey);
        $this->info('订单队列条数' . $total . " redis key " . $redisKey);
        while ($total > 0) {
            $orders = Redis::lrange($redisKey, 0, $batchSize - 1);
            if (empty($orders)) break;

            $trade_list = [];
            $order_list = [];
            $orderSnList = []; // 记录本批订单号
            $orderJsonMap = []; // 订单号=>原始json

            foreach ($orders as $orderJson) {
                $this->info('订单orderJson' . $orderJson);
                $order = json_decode($orderJson, true);
                if (!$order) continue;
                $trade = $order['trade'];
                $orderSn = $trade['tid'] ?? null; // 订单号唯一标识
                if (!$orderSn) continue;
                $orderSnList[] = $orderSn;
                $orderJsonMap[$orderSn] = $orderJson;
                $trade['order_list'] = $order['order_list'];
                $trade_list[] = $trade;
                foreach ($order['order_list'] as $od) {
                    $order_list[] = $od;
                }
            }
            Log::info('同步创建原始订单数据请求旺店通参数', [$order_list]);
            $c->putApiParam('shop_no', $shopNo);
            $c->putApiParam('switch', 0);
            $c->putApiParam('trade_list', json_encode($trade_list, JSON_UNESCAPED_UNICODE));
            $c->putApiParam('order_list', json_encode($order_list, JSON_UNESCAPED_UNICODE));

            Log::info('同步创建原始订单数据旺店通推送到旺店通的参数', [
                'shop_no' => $shopNo,
                'switch' => 0,
                'trade_list' => $trade_list,
                'order_list' => $order_list,
            ]);

            $result = $c->wdtOpenApi();
            Log::info('同步创建原始订单数据旺店通推送结果', [$result]);

            $resultArr = json_decode($result, true);
            $success = isset($resultArr['code']) && $resultArr['code'] == 0;

            // 先移除本批订单
            Redis::ltrim($redisKey, $batchSize, -1);

            if ($success) {
                // 推送成功，清理重试key
                foreach ($orderSnList as $orderSn) {
                    $retryKey = "order:push:retry:{$orderSn}";
                    Redis::del($retryKey);
                }
            } else {
                // 推送失败，处理重试
                foreach ($orderSnList as $orderSn) {
                    $retryKey = "order:push:retry:{$orderSn}";
                    $retryCount = Redis::incr($retryKey);
                    if ($retryCount < 3) {
                        // 放回队列尾部
                        Redis::rpush($redisKey, $orderJsonMap[$orderSn]);
                    } else {
                        Log::error("订单推送失败超过3次，order_sn: {$orderSn}", [
                            'order' => $orderJsonMap[$orderSn],
                            'result' => $resultArr,
                        ]);
                        Redis::del($retryKey); // 可选：清理重试key
                    }
                }
            }
            $total = Redis::llen($redisKey);
        }

        $this->info('同步创建原始订单数据订单推送任务执行完毕,待同步数量' . $total);
    }
}